package boboLang;

import java.util.Arrays;

/*
* 源码分析可参考：https://segmentfault.com/a/1190000004261063
* */
public class BoboStringBuffer extends BoboAbstractStringBuilder {
    /*
    * 缓存上一次调用toString方法时的字符数组，一旦BoboStringBuffer被修改，该缓存就会被置为空
    * */
    private transient char[] toStringCache;

    /*
    * 构造函数
    * */
    public BoboStringBuffer(){
        super(16);
    }
    public BoboStringBuffer(int capacity){
        super(capacity);
    }
    public BoboStringBuffer(BoboString str){
        super(str.length() + 16);
        append(str);
    }

    @Override
    public synchronized BoboStringBuffer append(BoboString str){
        toStringCache = null;
        super.append(str);
        return this;
    }

    @Override
    public synchronized String toString() {
        if (toStringCache == null){
            toStringCache = Arrays.copyOfRange(value, 0, count);
        }
        /*
        * 真正的源码是通过直接指向toStringCache的，这样效率更高
        * return new String(toStringCache, true);
        * */
        return new String(toStringCache);

    }
}
